﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.ServiceModel.Syndication;
using CarnetAnniversaires.Metier;

namespace RssAlerts
{
    public class RssAnniversaire : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/rss+xml";
            context.Response.ContentEncoding = Encoding.UTF8;
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.BufferOutput = false;
            string UserID = context.Request["UserId"] ;
            //todo récup le nom avec l'userid 
            string Name= UserID;
            System.IO.MemoryStream stream = FileBlobManager.GetFileInBlob(UserID);
            
            if (stream != null)
            {
                const int buffersize = 1024 * 16;
                byte[] buffer = new byte[buffersize];
                int count = stream.Read(buffer, 0, buffersize);
                while (count > 0)
                {
                    context.Response.OutputStream.Write(buffer, 0, count);
                    count = stream.Read(buffer, 0, buffersize);
                }
            }
            context.Response.End();
        }

        public static void AddAlert(Anniversaire Anniv,String Message)
        {
            System.IO.MemoryStream stream = FileBlobManager.GetFileInBlob(Anniv.PartitionKey);
            SyndicationItem Alert = new SyndicationItem("Anniversaire de " + Anniv.prenom + " " + Anniv.nom + " le " + Anniv.RowKey, Message, null);
            SyndicationFeed feed;
            if (stream!=null && stream.Length > 0)
            {
                //int count = 0;
                //byte[] byteArray = new byte[stream.Length];
                //// Read the remaining bytes, byte by byte.
                //while (count < stream.Length)
                //{
                //    byteArray[count++] =
                //        Convert.ToByte(stream.ReadByte());
                //}

                feed = SyndicationFeed.Load(System.Xml.XmlReader.Create(stream));
                List<SyndicationItem> Alerts = new List<SyndicationItem>();
                Alerts.Add(Alert);
                //feed.Items = Alerts.AsEnumerable();
                feed.Items.Concat(Alerts);
                
                FileBlobManager.DeleteFileInBlob(Anniv.PartitionKey);

            }
            else
            {
                feed = new SyndicationFeed("Mes alertes Anniversaire", "Les alertes pour les anniversaires", null);
                List<SyndicationItem> Alerts = new List<SyndicationItem>();
                Alerts.Add(Alert);
                feed.Items = Alerts.AsEnumerable();
                
            }
            feed.LastUpdatedTime = DateTime.Now;
            SyndicationFeedFormatter formatter = null;
            formatter = new Atom10FeedFormatter(feed);
            StringBuilder StringFeed = new StringBuilder();
            System.Xml.XmlWriter Writer = System.Xml.XmlWriter.Create(StringFeed);
            formatter.WriteTo(Writer);
            Writer.Flush();
            FileBlobManager.PutFileInBlob(System.Text.UTF8Encoding.Unicode.GetBytes(StringFeed.ToString()), Anniv.PartitionKey);
              


        }

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        #endregion
    }
}
